const $config = require('../../config');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const os = require('os');
const path = require('path');
const fs = require('fs');           //引用文件系统模块
const image = require("imageinfo"); //引用imageinfo模块

//获取本机IP
function getIPAdress() {
  const interfaces = os.networkInterfaces();
  for (let devName in interfaces) {
    let iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      let alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}
//获取文件集合
function readFileList(path, filesList) {
  const files = fs.readdirSync(path);
  files.forEach(function (item, index) {
    let stat = fs.statSync(path + item);
    if (stat.isDirectory()) {
      //递归读取文件
      readFileList(path + item + "/", filesList)
    } else {
      const obj = {};            //定义一个对象存放文件的路径和名字
      obj.path = path;           //路径
      obj.filename = item;       //名字
      filesList.push(obj);
    }
  })
}
class getFiles {
  //获取文件夹下的所有文件
  static getFileList(path) {
    const filesList = [];
    readFileList(path, filesList);
    return filesList;
  }
  //获取文件夹下的所有图片
  static getImageFiles(path) {
    const imageList = [];
    this.getFileList(path).forEach((item) => {
      let ms = image(fs.readFileSync(item.path + item.filename));
      ms.mimeType && (imageList.push(item.filename))
    });
    return imageList;
  }
};



module.exports = {
  uploadCollections: async (ctx, next) => {
    const token = ctx.request.header.token;
    await jwt.verify(token, $config.tokenSecret, async (err, resultToken) => { // resultToken 解析token值
      if (err) {  //  时间失效的时候/ 伪造的token
        ctx.body = {
          success: false,
          result: '验证已过期！',
          ...err
        };
        return;
      }
      // const srcImgList=getFiles.getImageFiles(path.join(__dirname,'../../public/'));   //只获取图片集合
      const srcImgPathList = getFiles.getFileList(path.join(__dirname, '../../public/')); //获取完整图片路径集合
      const srcNewList = [];
      srcImgPathList.forEach((item, index) => {
        const path = item.path.split('\\');
        const pathIndex = path.reverse().findIndex(item => item === 'public');
        srcNewList.push({
          src: 'http://' + getIPAdress() + ':' + $config.servePort + '/' + path.reverse().slice(-pathIndex).join('/') + item.filename
        })
      });
      ctx.body = {
        success: true,
        message: '',
        result: srcNewList,
      };
    })
  }
};
